package com.yuelao.yuelao_backend.util;

import com.yuelao.yuelao_backend.common.BizException;
import com.yuelao.yuelao_backend.common.ErrorCode;
import com.yuelao.yuelao_backend.entity.User;
import com.yuelao.yuelao_backend.service.security.CustomUserDetails;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * 用户上下文工具类
 * 用于获取当前登录用户的信息
 */
public class UserContextUtil {

    /**
     * 获取当前登录用户的ID
     *
     * @return 当前用户ID
     */
    public static Long getCurrentUserId() {
        User currentUser = getCurrentUser();
        return currentUser.getId();
    }

    /**
     * 获取当前登录用户的信息
     *
     * @return 当前用户实体
     */
    public static User getCurrentUser() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof CustomUserDetails) {
            CustomUserDetails userDetails = (CustomUserDetails) principal;
            return userDetails.getUser();
        } else {
            throw new BizException(ErrorCode.NOT_LOGIN_ERROR, "用户未登录");
        }
    }

    /**
     * 获取当前登录用户的手机号
     *
     * @return 当前用户手机号
     */
    public static String getCurrentUserPhone() {
        User currentUser = getCurrentUser();
        return currentUser.getPhone();
    }

    /**
     * 获取当前登录用户的昵称
     *
     * @return 当前用户昵称
     */
    public static String getCurrentUserNickname() {
        User currentUser = getCurrentUser();
        return currentUser.getNickname();
    }
}